package cn.bonoon.controllers.parsers;

import javax.servlet.http.HttpServletRequest;

import org.batatasframework.web.RequestParameterReader;

import cn.bonoon.kernel.events.PanelEvent;
import cn.bonoon.kernel.menus.ChannelDefinition;
import cn.bonoon.kernel.menus.ModuleDefinition;
import cn.bonoon.kernel.menus.ModuleManager;
import cn.bonoon.kernel.menus.TabsDefinition;
import cn.bonoon.kernel.menus.privileges.PrivilegeInspector;
import cn.bonoon.kernel.security.LogonUser;
import cn.bonoon.kernel.support.services.PrivilegeSupport;
import cn.bonoon.kernel.web.controllers.PanelParser;
import cn.bonoon.kernel.web.models.LayoutModel;

public class TabsPanelParser implements PanelParser{

	protected final ModuleManager moduleManager;
	protected final PrivilegeSupport privilegeSupport;
	
	public TabsPanelParser(ModuleManager moduleManager, PrivilegeSupport privilegeSupport) {
		this.moduleManager = moduleManager;
		this.privilegeSupport = privilegeSupport;
	}

	@Override
	public PanelEvent parse(String mid, HttpServletRequest request, LogonUser user) throws Exception {
		
		LayoutModel model = new LayoutModel(mid, request, moduleManager);
		TabsDefinition ti = moduleManager.tab(mid);
		PrivilegeInspector privilege= privilegeSupport.privilege(user, ti);
		
		ModuleDefinition module = ti.getModule();
		model.initLayout(ti.navigation(), module.getStyle(), ti.getDescribe());
		
		ChannelDefinition channel = ti.getChannel();
		String selectedChannel = channel.getId();
		RequestParameterReader reader = RequestParameterReader.valueOf(request);
		model.buildChannel(module, user, reader, privilege, selectedChannel);

		model.buildMenu(user, reader, channel, privilege, ti.getId());
		return new PanelEvent(model, ti, user, privilege);
	}

}
